import { ref, markRaw, onMounted } from 'vue';
import { GetTaskDataSummaryListParams } from '@/apis/eci/carbonManagement/model/dataListModel';
import { getTaskDataSelectionList } from '@/apis/eci/carbonManagement/dataList';
import { SearchOptionsType } from '@/components/CPageTable';
import { useRoute } from 'vue-router';
import { VxeTablePropTypes } from '@xfchenju/vxe-table';
import { useCellRowMerge } from '@/hooks/useCellRowMerge';

export const useList = (props: any) => {
  const route = useRoute();
  const loading = ref(false);
  const cellMergeMap = ref<Record<string, any>>({});
  const mergeCellsList = ref<VxeTablePropTypes.MergeCells>([]);
  const { handleCellMerge, handleTransformMapToList } = useCellRowMerge();
  const fields = [
    'emissionScope',
    'emissionCategory',
    'ghgSourceName',
    'sourceName',
    'materialName'
  ];
  const fieldToColMap = {
    emissionScope: 0,
    emissionCategory: 1,
    ghgSourceName: 2,
    sourceName: 3,
    materialName: 4
  };
  const dataSource = ref<any[]>([]);
  // 页面标题
  const taskNo = route.query.taskNo as any;
  // 搜索配置
  const searchOptions: SearchOptionsType[] = markRaw([]);
  onMounted(() => {
    loadData();
  });
  function loadData() {
    const params: GetTaskDataSummaryListParams = {
      taskNo,
      standard: props.standard
    };
    loading.value = true;
    getTaskDataSelectionList(params)
      .then((res: any) => {
        if (res) {
          cellMergeMap.value = handleCellMerge(res, fields);
          mergeCellsList.value = handleTransformMapToList(cellMergeMap.value, fieldToColMap);
          dataSource.value = res;
        } else {
          dataSource.value = [];
        }
        loading.value = false;
      })
      .catch(error => {
        console.log('error', error);
        loading.value = false;
        dataSource.value = [];
      });
  }
  const mergeCells = ref([{ row: 0, col: 4, rowspan: 1, colspan: 4 }]);

  const extraTableOption = {
    maxHeight: '540'
  };
  return {
    // 头部右侧筛选项配置
    searchOptions,
    loadData,
    dataSource,
    loading,
    extraTableOption,
    mergeCellsList
  };
};
